<template>
  <div class="upload-file">
    <form>
      <label for="file">请选择要上传的文件</label>
      <input type="file"
             name="file"
             class="file-btn"
             multiple>
      <br />
      <button type="button"
              class="submit-btn"
              @click="chooseFiles"
              value="上传">上传</button>
    </form>

    <ul class="result-wrapper">
      <li v-for="item in fileList"
          :key="item.id">
        <span>《 {{item.name}} 》上传结果：</span>
        <span>{{item.result}}</span>
      </li>
    </ul>
  </div>
</template>

<script>
import { ipcRenderer } from 'electron'
export default {
  name: 'upload-file',
  data () {
    return {
      fileList: []
    }
  },
  methods: {
    chooseFiles () {
      this.fileList = []
      const files = document.querySelector('input[type=file]').files
      for (var i = 0; i < files.length; i++) {
        this.fileList.push({
          id: i,
          name: files[i].name,
          result: '**'
        })

        // 渲染进程发送异步消息给主进程
        ipcRenderer.send('asynchronous-message', { index: i, filePath: files[i].path })
      }
    }
  },
  mounted () {
    ipcRenderer.on('asynchronous-reply', (event, data) => {
      const { index, code } = data
      const file = this.fileList[index]
      if (code === 0) {
        this.fileList.splice(index, 1, { ...file, result: '成功' })
      } else {
        this.fileList.splice(index, 1, { ...file, result: '失败' })
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.upload-file {
  .file-btn {
    margin: 15px 10px; //node .electron-vue/dev-runner.js
  }
  .submit-btn {
    border-radius: 8px;
    width: 50px;
    height: 26px;
    background: #fff;
    border-width: 1px;
    font-size: 12px;
    outline: none;
  }
  .result-wrapper {
    li {
      list-style: none;
      margin: 5px 0;
    }
  }
}
</style>
